package com.tul.exercise.base.swing.components;

import com.tul.exercise.base.swing.SwingConsole;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @Description 《java编程思想》第22章 示例16：
 * <p>
 * 下拉框
 **/
public class ComboBoxes extends JFrame {
    private String[] description = {"Ebullient", "Obtuse", "Recalcitrant", "Brilliant", "Somnescent"};

    private JTextField text = new JTextField(15);
    private JComboBox selectText = new JComboBox();
    private JButton addItem = new JButton("Add items");
    private int count = 0;

    public ComboBoxes() {
        for (int i = 0; i < 4; i++) {
            selectText.addItem(description[count++]);
        }

        text.setEditable(false);

        addItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (count < description.length) {
                    selectText.addItem(description[count++]);
                }
            }
        });

        selectText.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                text.setText("index: " + selectText.getSelectedIndex() + "   " +
                        ((JComboBox) e.getSource()).getSelectedItem());
            }
        });

        setLayout(new FlowLayout());
        add(text);
        add(selectText);
        add(addItem);
    }

    public static void main(String[] args) {
        SwingConsole.run(new ComboBoxes(), 200, 175);
    }
}
